package com.ks.api.service;

import com.ks.api.entity.CultivationLevel;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
public class DataImportService {

    @Autowired
    private CultivationLevelService cultivationLevelService;

    /**
     * 从JSON文件导入修仙等级数据
     * @return 导入记录数
     */
    @Transactional
    public int importCultivationLevelsFromJson() {
        try {
            // 清空现有数据
            cultivationLevelService.deleteAllLevels();
            
            ObjectMapper objectMapper = new ObjectMapper();
            ClassPathResource resource = new ClassPathResource("static/levelData.json");
            InputStream inputStream = resource.getInputStream();
            
            List<CultivationLevel> levels = objectMapper.readValue(
                inputStream, 
                new TypeReference<List<CultivationLevel>>() {}
            );
            
            int count = 0;
            for (CultivationLevel level : levels) {
                if (cultivationLevelService.addLevel(level)) {
                    count++;
                }
            }
            
            return count;
        } catch (IOException e) {
            throw new RuntimeException("导入修仙等级数据失败", e);
        }
    }
} 